import 'dart:io';

import 'package:dio/dio.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_cupertino_datetime_picker/flutter_cupertino_datetime_picker.dart';
import 'package:hitutor/Util/DateUtil.dart';
import 'package:hitutor/Util/Global.dart';
import 'package:hitutor/Util/HttpGo.dart';
import 'package:hitutor/Util/MyColor.dart';
import 'package:hitutor/Util/PageUtil.dart';
import 'package:hitutor/Widget/Check.dart';
import 'package:hitutor/Widget/ChooserBox.dart';
import 'package:hitutor/Widget/MyButton.dart';
import 'package:hitutor/Widget/MyDialog.dart';
import 'package:hitutor/Widget/MyImage.dart';
import 'package:hitutor/Widget/MyInput.dart';
import 'package:hitutor/Widget/MyPage.dart';

class ApplyPause extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _ApplyPause();
  }
}

class _ApplyPause extends State<ApplyPause> {
  static int FirstApply = 1;
  static int Resume = 2;
  static int ApplyAgain = 4;
  static int NoClass = 5;
  int pageType = 0;

  @override
  void initState() {
    WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
      getStatus();
    });
    super.initState();
  }

  getStatus() {
    HttpGo(context).get("/PlatformSuspend/GetPlatformSuspendData?studentId=${Global.studentId}", {}, (data) {
      pageType = data["qualifications"];
      setState(() {});
    }, (code, error) => showToast(error));
  }

  @override
  Widget build(BuildContext context) {
    Widget body = Container();
    if (pageType == NoClass) {
      body = Text("目前無有效課程，故無法申請帳號暫停");
    } else if (pageType == Resume) {
      body = ResumeBody();
    } else if (pageType == FirstApply || pageType == ApplyAgain) {
      body = ApplyBody(pageType == FirstApply);
    }
    return MyPage(pageType == Resume ? "申請提早恢復上課" : "申請帳號暫停", Container(padding: EdgeInsets.all(16), child: body)
        // rightWidgets: [LocalImage("menu-alt.png", width: 40, height: 40, padding: EdgeInsets.all(10), onTap: choosePage)],
        );
  }
}

class ResumeBody extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _ResumeBody();
  }
}

class _ResumeBody extends State<ResumeBody> {
  String resumeTime = "";
  String resumeTimeUtc = "";
  DateTime now = DateTime.now();

  ChooseStartTime() {
    DatePicker.showDatePicker(context,
        dateFormat: "yyyy年 MM月 dd日",
        //通过空格设置滚轮数量
        initialDateTime: DateTime(now.year, now.month, now.day),
        minDateTime: now,
        pickerTheme: DateTimePickerTheme(confirm: Text("完成", style: TextStyle(fontSize: 14, color: MyColor.C58))),
        onConfirm: (DateTime dateTime, List<int> selectedIndex) {
      resumeTime = getStrTime(dateTime, DateUtil.YMD);
      resumeTimeUtc = getUtcTime(dateTime);
      setState(() {});
    });
  }

  apply() {
    if (resumeTimeUtc.isEmpty) {
      showToast("請選擇您要恢復上課的時間");
      return;
    }
    HttpGo(context, json: false, receiveTime: 60000).post("/PlatformSuspend/ApplyPlatformSuspend/", {
      "operatorUserId": Global.userId,
      "studentId": Global.studentId,
      "reStartDate": resumeTimeUtc,
      "status": 2,
    }, (data) {
      PageUtil().back(context);
    }, (code, error) => showToast(error));
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
      Text("請選擇您要恢復上課的時間", style: TextStyle(fontSize: 13, color: MyColor.C58)),
      Container(margin: EdgeInsets.fromLTRB(0, 8, 0, 24), child: ChooserBox(resumeTime, onTap: ChooseStartTime)),
      Button("確定", height: 32, width: double.infinity, bgColor: MyColor.Green, onTap: apply)
    ]));
  }
}

class ApplyBody extends StatefulWidget {
  bool isFirst = false;

  ApplyBody(this.isFirst);

  @override
  State<StatefulWidget> createState() {
    return _ApplyBody();
  }
}

class _ApplyBody extends State<ApplyBody> {
  bool agree = false;
  DateTime? startTime;
  DateTime? endTime;

  int subDays = 0;

  DateTime now = DateTime.now();

  ChooseStartTime() {
    DatePicker.showDatePicker(context,
        dateFormat: "yyyy年 MM月 dd日",
        //通过空格设置滚轮数量
        initialDateTime: DateTime(now.year, now.month, now.day),
        minDateTime: now,
        pickerTheme: DateTimePickerTheme(confirm: Text("完成", style: TextStyle(fontSize: 14, color: MyColor.C58))),
        onConfirm: (DateTime dateTime, List<int> selectedIndex) {
      if (endTime != null) {
        var difference = endTime!.difference(dateTime);
        if (difference.inDays < 1) {
          showToast("結束時間需要大於開始時間");
          return;
        }
        subDays = difference.inDays;
      }
      startTime = dateTime;
      setState(() {});
    });
  }

  ChooseEndTime() {
    DatePicker.showDatePicker(context,
        dateFormat: "yyyy年 MM月 dd日",
        //通过空格设置滚轮数量
        initialDateTime: DateTime(now.year, now.month, now.day),
        minDateTime: now,
        pickerTheme: DateTimePickerTheme(confirm: Text("完成", style: TextStyle(fontSize: 14, color: MyColor.C58))),
        onConfirm: (DateTime dateTime, List<int> selectedIndex) {
      if (startTime != null) {
        var difference = dateTime.difference(startTime!);
        if (difference.inDays < 1) {
          showToast("結束時間需要大於開始時間");
          return;
        }
        subDays = difference.inDays;
      }
      endTime = dateTime;
      setState(() {});
    });
  }

  int getSubDays() {
    var difference = endTime?.difference(startTime!);
    return difference?.inDays ?? 0;
  }

  List<MultipartFile> uploadFiles = [];

  chooseFile() async {
    FilePickerResult? result = await FilePicker.platform.pickFiles();
    if (result != null && result.files.single.path != null) {
      MultipartFile file = await MultipartFile.fromFile(result.files.single.path!);
      uploadFiles.add(file);
      setState(() {});
    }
  }

  TextEditingController reasonController = TextEditingController();

  apply() async {
    if (startTime == null || endTime == null) {
      showToast("請選擇您要暫停的時間");
      return;
    }
    if (!agree) {
      showToast("請閱讀並同意帳號暫停規章");
      return;
    }
    String startTimeUtc = getUtcTime(startTime!);
    String endTimeUtc = getUtcTime(endTime!);
    String reason = reasonController.text;
    Map<String, dynamic> params = {
      "operatorUserId": Global.userId,
      "studentId": Global.studentId,
      "startDate": startTimeUtc,
      "endDate": endTimeUtc,
    };
    if (widget.isFirst) {
      params["status"] = 1;
    } else {
      if (reason.isEmpty) {
        showToast("請填寫暫停理由");
        return;
      }
      if (uploadFiles.length < 1) {
        showToast("請上傳憑證文件");
        return;
      }
      params["status"] = 3;
      params["reason"] = reason;
      params["File"] = uploadFiles;
    }

    HttpGo(context, json: false, receiveTime: 60000).post("/PlatformSuspend/ApplyPlatformSuspend/", params, (data) {
      PageUtil().back(context);
    }, (code, error) => showToast(error));
  }

  @override
  void initState() {
    WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {});
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
        child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
      Text("請選擇您要暫停的時間", style: TextStyle(fontSize: 13, color: MyColor.C58)),
      Padding(
          padding: EdgeInsets.fromLTRB(0, 8, 0, 8),
          child: Row(children: [
            Expanded(child: ChooserBox(getStrTime(startTime, DateUtil.YMD), onTap: ChooseStartTime)),
            Text("　~　"),
            Expanded(child: ChooserBox(getStrTime(endTime, DateUtil.YMD), onTap: ChooseEndTime)),
          ])),
      Text("暫停總天數", style: TextStyle(fontSize: 13, color: MyColor.C58)),
      Container(
          decoration: Global.getBg(MyColor.F2, 5),
          padding: EdgeInsets.fromLTRB(4, 0, 8, 0),
          margin: EdgeInsets.fromLTRB(0, 8, 0, 8),
          alignment: Alignment.centerLeft,
          height: 28,
          width: double.infinity,
          child: Text("$subDays", style: TextStyle(fontSize: 12, color: MyColor.C58))),
      Visibility(
          visible: !widget.isFirst,
          child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
            Text("請填寫暫停理由", style: TextStyle(fontSize: 13, color: MyColor.C58)),
            Container(
                decoration: Global.getBg(MyColor.F2, 5),
                padding: EdgeInsets.all(8),
                margin: EdgeInsets.fromLTRB(0, 8, 0, 8),
                height: 100,
                width: double.infinity,
                child: NormalInput(maxLines: 0, controller: reasonController)),
            GestureDetector(
                onTap: chooseFile,
                child: Row(children: [
                  LocalImage("cloud-upload-g.png", width: 32, height: 16),
                  Text("上傳文件", style: TextStyle(color: MyColor.Green))
                ]))
          ])),
      ListView.builder(
          shrinkWrap: true,
          itemCount: uploadFiles.length,
          itemBuilder: (BuildContext context, int index) {
            return ItemFile(uploadFiles[index].filename, delFile: () {
              uploadFiles.removeAt(index);
              setState(() {});
            });
          }),
      AgreeTerm(agree, onTap: () {
        agree = !agree;
        setState(() {});
      }),
      Button(widget.isFirst ? "確定" : "上傳審核", height: 32, width: double.infinity, bgColor: MyColor.Green, onTap: apply)
    ]));
  }
}

class ItemFile extends StatelessWidget {
  String? fileName;
  Function()? delFile;

  ItemFile(this.fileName, {this.delFile});

  @override
  Widget build(BuildContext context) {
    return Container(
        padding: EdgeInsets.fromLTRB(0, 4, 0, 4),
        child: Row(children: [
          Expanded(child: Text("$fileName", style: TextStyle(color: MyColor.Green, fontWeight: FontWeight.bold))),
          LocalImage("del.png", width: 10, padding: EdgeInsets.all(8), onTap: delFile)
        ]));
  }
}

//done
class AgreeTerm extends StatelessWidget {
  bool agree;
  Function()? onTap;

  AgreeTerm(this.agree, {this.onTap});

  @override
  Widget build(BuildContext context) {
    return Container(
        margin: EdgeInsets.fromLTRB(8, 32, 0, 24),
        child: Row(children: [
          GestureDetector(onTap: onTap, child: Check(agree)),
          Text(" 我同意", style: TextStyle(color: MyColor.C7D)),
          TextBtn("帳號暫停規章", style: TextStyle(color: MyColor.BlueTxt), onTap: () {
            HttpGo(context).get("/PlatformSuspend/GetPlatformSuspendRegulation", {}, (data) {
              showWidgetDialog(context, PauseTerm(data["content"]));
            }, (code, error) => showToast(error));
          }),
          Text("。", style: TextStyle(color: MyColor.C7D))
        ]));
  }
}

class PauseTerm extends StatelessWidget {
  String term = "";

  PauseTerm(this.term);

  @override
  Widget build(BuildContext context) {
    return Container(
        decoration: Global.getWhiteBg(8),
        padding: EdgeInsets.all(16),
        child: Column(children: [
          Container(
              height: 40,
              color: MyColor.Orange,
              alignment: Alignment.center,
              child: Text("帳號暫停規章", style: TextStyle(fontSize: 22, color: MyColor.White, fontWeight: FontWeight.bold))),
          Container(height: 12),
          Expanded(child: SingleChildScrollView(child: Text(term, style: TextStyle(fontSize: 14, color: MyColor.C7D, height: 1.5)))),
          Container(height: 12),
          Button("確認", width: 72, height: 32, bgColor: MyColor.Orange, onTap: () {
            PageUtil().back(context);
          })
        ]));
  }
}
